/**
 * @description 产品-行业 关联表控制器
 * @author 韩
 */

const model = require("../../model/link/product_profession_link")
const { getFilter } = require("../../utils/setFilter")

//保存一个关联数据
const controller_save = async ({
    productionId = undefined,
    professionId = undefined,
}) => {
    return new Promise(async (resolve, reject) => {
        const params = {
            productId: productionId,
            professionId: professionId,
        }

        const findResult = await model.findOneAndUpdate({ productionId: productionId }, {
            $set: {
                ...params
            }
        }, { new: true })
        if (findResult == null) {
            let res = model.create({ ...params });
            if (res) {
                resolve(true)
            } else {
                reject(false)
            }
        } else {
            resolve(false)
        }
    })


}


// 查询列表 
const controller_find = async ({ current, pageSize, productionId, categoryId, }) => {

    try {
        let params = {
            productionId, categoryId,
        }
        let filter = getFilter(params)
        const list = await model.find(filter).sort({ createDate: 0 }).skip((current - 1) * pageSize).limit(pageSize);
        const totalCount = await model.countDocuments(filter);
        return {
            code: 0,
            msg: "查询成功",
            data: {
                list,
                totalCount
            }
        }
    } catch (error) {
        return {
            code: 1,
            msg: "查询失败",
        }
    }
}


/**@description 根据id查详情 */
const controller_get = async ({ productId, }) => {
    try {
        const res = await model.findOne({
            productId
        })
        if (res) {
            const { productId, professionId } = res;
            return {
                code: 0,
                msg: "查询成功",
                data: {
                    productId, professionId
                }
            }
        } else {
            return {
                code: 100,
                msg: "未找到对应数据"
            }
        }
    } catch (error) {
        console.log("查详情报错：", error)
        return {
            code: 100,
            msg: "查详情报错" + error
        }
    }
}

// 删除
const controller_delete = async ({ _ids = [], _id = undefined }) => {
    try {
        const res = await model.deleteMany({ _id: _ids })

        if (res) {
            return {
                code: 0,
                msg: `删除成功`
            }
        } else {
            return {
                code: 100,
                msg: `删除失败`
            }
        }
    } catch (error) {
        console.log("删除控制器出错", error)
        return {
            code: 100,
            msg: `删除出错` + error
        }

    }

}
module.exports = {
    controller_save,
    controller_find,
    controller_get,
    controller_delete,
}